#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：NoBad 
@File    ：view.py
@Author  ：LYP
@Date    ：2025/10/30 13:26 
@description :
"""
from rest_framework import serializers
# from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiParameter
from django.shortcuts import get_object_or_404
from models.models import Product, PromptTemplate
from tool.tools import CustomStatus, logger
from tool.base_views import BaseViewSet
from tool.utils import ApiResponse, CustomPagination
from django.utils.translation import gettext as _

class ProductSerializer(serializers.ModelSerializer):
    """
    商品序列化器
    """
    name = serializers.CharField(required=False)
    product_type = serializers.CharField(required=False)
    logo_url = serializers.URLField(required=False)
    product_code = serializers.CharField(required=False)

    class Meta:
        model = Product
        fields = '__all__'
        read_only_fields = ('created_time', 'updated_time')

    def validate_price(self, value):
        """
        验证商品价格不能为负数
        """
        if value < 0:
            raise serializers.ValidationError(_("商品价格不能为负数"))
        return value

    def validate_product_code(self, value):
        """
        验证商品编号唯一性
        """
        if Product.objects.filter(product_code=value).exclude(
                pk=self.instance.pk if self.instance else None
        ).exists():
            raise serializers.ValidationError(_("商品编号已存在"))
        return value


@extend_schema(tags=["商品管理"])
@extend_schema_view(
    list=extend_schema(
        summary="获取商品列表",
        description="返回所有商品的信息列表",
        responses={200: ProductSerializer(many=True)},
        parameters=[
            OpenApiParameter(name="name", description="商品名称", required=False),
            OpenApiParameter(name="product_type", description="商品类型", required=False)
        ]
    ),
    create=extend_schema(
        summary="创建商品",
        description="创建一个新的商品",
        request=ProductSerializer,
        responses={201: ProductSerializer},
    )
)
class ProductListView(BaseViewSet):
    """
    商品列表视图 - 处理商品的增删改查
    """

    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            # 使用自定义分页响应
            return self.get_paginated_response(serializer.data)
        # 如果没有分页，返回普通响应
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)

    def get_queryset(self):
        # 获取查询参数
        name = self.request.GET.get('name', None)
        product_type = self.request.GET.get('product_type', None)

        # 构建查询条件
        queryset = Product.objects.all()

        if product_type:
            PromptTemplate.objects.filter(template_type__icontains=product_type)
            queryset = queryset.filter(product_type=product_type)

        if name:
            queryset = queryset.filter(name__icontains=name)

        return queryset

    def get_serializer_class(self):
        return ProductSerializer

    def post(self, request):
        """
        创建商品
        """
        try:
            serializer = ProductSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(
                    CustomStatus.CREATED.to_response(data=serializer.data),
                    status=status.HTTP_201_CREATED
                )
            else:
                return Response(
                    CustomStatus.VALIDATION_ERROR.to_response(data=serializer.errors),
                    status=status.HTTP_400_BAD_REQUEST
                )
        except Exception as e:
            logger.error(f"创建商品失败: {str(e)}")
            return Response(
                CustomStatus.INTERNAL_ERROR.to_response(),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@extend_schema(tags=["商品管理"])
@extend_schema_view(
    get=extend_schema(
        summary="获取商品详情",
        description="根据商品ID获取单个商品的详细信息",
        responses={200: ProductSerializer}
    ),
    put=extend_schema(
        summary="更新商品",
        description="根据商品ID更新商品信息",
        request=ProductSerializer,
        responses={200: ProductSerializer}
    ),
    delete=extend_schema(
        summary="删除商品",
        description="根据商品ID删除商品",
        responses={204: "删除成功"}
    )
)
class ProductDetailView(BaseViewSet):
    """
    商品详情视图
    """

    def get(self, request, pk):
        """
        获取商品详情
        """
        try:
            product = get_object_or_404(Product, pk=pk)
            serializer = ProductSerializer(product)
            return Response(
                CustomStatus.SUCCESS.to_response(data=serializer.data)
            )
        except Product.DoesNotExist:
            return Response(
                CustomStatus.NOT_FOUND.to_response(),
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"获取商品详情失败: {str(e)}")
            return Response(
                CustomStatus.INTERNAL_ERROR.to_response(),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def put(self, request, pk):
        """
        更新商品
        """
        try:
            product = get_object_or_404(Product, pk=pk)
            serializer = ProductSerializer(product, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(
                    CustomStatus.UPDATED.to_response(data=serializer.data)
                )
            else:
                return Response(
                    CustomStatus.VALIDATION_ERROR.to_response(data=serializer.errors),
                    status=status.HTTP_400_BAD_REQUEST
                )
        except Product.DoesNotExist:
            return Response(
                CustomStatus.NOT_FOUND.to_response(),
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"更新商品失败: {str(e)}")
            return Response(
                CustomStatus.INTERNAL_ERROR.to_response(),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def delete(self, request, pk):
        """
        删除商品
        """
        try:
            product = get_object_or_404(Product, pk=pk)
            product.delete()
            return Response(
                CustomStatus.DELETED.to_response()
            )
        except Product.DoesNotExist:
            return Response(
                CustomStatus.NOT_FOUND.to_response(),
                status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"删除商品失败: {str(e)}")
            return Response(
                CustomStatus.INTERNAL_ERROR.to_response(),
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
